package main

import (
	"gRPC_Client/client"
	"gRPC_Client/helper"
	"google.golang.org/grpc"
	"log"
	"math/rand"
	"time"
)

const (
	username        = "admin"
	password        = "secret"
	refreshDuration = 30 * time.Second
	Address         = "127.0.0.1:8888"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

var imagePath = "tmp/laptop.jpg"

func authMethods() map[string]bool {
	const laptopServicePath = "/services.LaptopService/"

	return map[string]bool{
		laptopServicePath + "CreateLaptop": true,
		laptopServicePath + "UploadImage":  true,
		laptopServicePath + "RateLaptop":   true,
	}
}

func main() {
	// TLS连接
	//从证书相关文件中读取和解析信息，得到证书公钥、密钥对
	transportOption := grpc.WithTransportCredentials(helper.GetClientCreds())
	conn1, err := grpc.Dial(Address, transportOption) //连接服务端,dial:拨号
	if err != nil {
		log.Fatal("cannot dial server: ", err)
	}
	defer conn1.Close()

	authClient := client.NewAuthClient(conn1, username, password)
	interceptor, err := client.NewAuthInterceptor(authClient, authMethods(), refreshDuration)
	if err != nil {
		log.Fatal("cannot create auth interceptor: ", err)
	}
	conn2, err := grpc.Dial(
		Address,
		transportOption,
		grpc.WithUnaryInterceptor(interceptor.Unary()),
		grpc.WithStreamInterceptor(interceptor.Stream()))
	if err != nil {
		log.Fatal("cannot dial server: ", err)
	}
	laptopClient := client.NewLaptopClient(conn2)

	laptop := client.NewLaptop()
	laptopClient.CreateLaptop(laptop)

	laptopClient.SearchLaptop()

	laptopClient.UploadImage(imagePath)

	laptopClient.RatingLaptop()

}
